package com.bee.gateway.server.listener;

import com.alibaba.fastjson.JSON;
import com.bee.commons.cache.CacheService;
import com.bee.commons.constants.Constants;
import com.bee.gateway.common.constants.GatewayRedisConst;
import com.bee.gateway.common.dto.MsgContentDTO;
import com.bee.gateway.common.enums.RoutesMsgTypeEnum;
import com.bee.gateway.server.service.AuthService;
import com.bee.gateway.server.service.RoutesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * 路由消息订阅，监听路由增删改和重载
 * @author Damin.yang
 * @date 2019/07/30 14:46
 */
@Component
@Slf4j
public class IgnoreUriSubscriberListener implements MessageListener {

    @Autowired
    private StringRedisSerializer stringRedisSerializer;
    @Autowired
    private GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer;

    @Autowired
    private RoutesService routesService;
    @Autowired
    private AuthService authService;
    @Autowired
    private CacheService cacheService;

    @Override
    public void onMessage(Message message, byte[] bytes) {

        String channel = stringRedisSerializer.deserialize(message.getChannel());
        MsgContentDTO msgContentDTO = null;
        try {
            msgContentDTO = jackson2JsonRedisSerializer.deserialize(message.getBody(), MsgContentDTO.class);
        } catch (SerializationException e) {
            log.error(">>> error parse message:", e);
        }
        if (msgContentDTO == null) {
            log.error(">>> message is null");
            return;
        }
        log.debug(">>> channel:{},msg:{}", channel, JSON.toJSON(msgContentDTO));

        if (GatewayRedisConst.GATEWAY_IGNORE_AUTH_CHANNEL.equals(channel)) {
            if (RoutesMsgTypeEnum.SAVE.name().equals(msgContentDTO.getMsgType())) {
                String[] uris = msgContentDTO.getContent().split(",");
                if (uris.length == Constants.TWO) {
                    authService.updateUri(uris[0], uris[1]);
                } else {
                    authService.addUri(uris[0]);
                }
            } else if (RoutesMsgTypeEnum.DELETE.name().equals(msgContentDTO.getMsgType())) {
                authService.deleteUri(msgContentDTO.getContent());
            } else if (RoutesMsgTypeEnum.OVERLOAD.name().equals(msgContentDTO.getMsgType())) {
                routesService.loadRouteDefinition();
            } else {
                log.error(">>> no match RoutesMsgTypeEnum");
            }
        }

    }
}
